<template>
	<div class='noticeMaintain-container'>
		<vxe-grid ref='vxeGridRef' v-bind='gridConfig'>
			<template v-slot:form>
				<n-flex justify='space-evenly' :wrap='false'>
					<n-form-item label='公告编号' path='noticeCode'
								 :show-label='false' :show-feedback='false'>
						<n-input v-model:value='gridConfig.formConfig!.data.id' placeholder='请输入公告编号'
								 :style='{width:"220px"}' clearable/>
					</n-form-item>
					<n-form-item label='公告标题' path='title'
								 :show-label='false' :show-feedback='false'>
						<n-input v-model:value='gridConfig.formConfig!.data.title' placeholder='请输入公告标题'
								 clearable/>
					</n-form-item>
					<n-form-item :show-label='false' :show-feedback='false'>
						<n-button round strong :bordered='false'
								  type='success' @click='initGrid'>
							查询
						</n-button>
						<n-button round strong :bordered='false'
								  type='info' @click='reset'>
							重置
						</n-button>
					</n-form-item>
				</n-flex>
			</template>
			<template v-slot:toolbar_buttons>
				<n-button round @click='add()' title='新增'>
					<template v-slot:icon>
						<i class='fa fa-plus'/>
					</template>
				</n-button>
			</template>
			<template v-slot:toolbar_tools>
				<div class='vxe-custom--wrapper'>
					<n-button circle @click='initGrid'>
						<template v-slot:icon>
							<i class='fa fa-refresh'/>
						</template>
					</n-button>
				</div>
			</template>
			<template v-slot:operate='{ row }'>
				<!--<n-button round @click='detail(row)' title='发布'>
					<template v-slot:icon>
						<i class='fa fa-info'/>
					</template>
				</n-button>-->
				<n-button round @click='edit(row)' title='编辑'>
					<template v-slot:icon>
						<i class='fa fa-edit'/>
					</template>
				</n-button>
				<n-button round @click='remove(row)' title='删除'>
					<template v-slot:icon>
						<i class='fa fa-remove'/>
					</template>
				</n-button>
			</template>
		</vxe-grid>
	</div>
	<AddModal ref='addModalRef' v-bind='addModalConfig'/>
	<EditModal ref='editModalRef' v-bind='editModalConfig'/>
	<InfoModal ref='infoModalRef' v-bind='infoModalConfig'/>
</template>
<script lang='ts' setup>
import { defineAsyncComponent, onBeforeMount, onMounted, reactive, ref } from 'vue';
import { VxeGridInstance, VxeGridProps } from 'vxe-table';
import axios from '@/config/axios/index.ts';
import type { JsonResultProps } from '#/JsonResult.d.ts';
import { VxeGrid, VxeUI } from '@/config/vxe/index.ts';
import type {
	SystemNoticeInfoProps, SystemNoticeProps
} from '#/src/components/page/systemManager/noticeMaintain/SystemNoticeProps.d.ts';
// -------------------------------------------------------------------------------------
const AddModal = defineAsyncComponent(() => import('./addModal.vue'));
const EditModal = defineAsyncComponent(() => import('./editModal.vue'));
const InfoModal = defineAsyncComponent(() => import('./infoModal.vue'));
// -------------------------------------------------------------------------------------
const gridConfig = reactive<VxeGridProps>({
	loading        : false,
	height         : 'auto',
	align          : 'center',
	keyboardConfig : { isArrow : true },
	pagerConfig    : {
		currentPage : 1,
		pageSize    : 20,
		total       : 0
	},
	toolbarConfig  : {
		custom : {
			icon : 'fa fa-cog'
		}
	},
	formConfig     : {
		data : {
			noticeCode : null,
			title      : null
		}
	},
	columns        : [
		{
			field        : 'sort',
			title        : '序号',
			showOverflow : 'tooltip'
		},
		{
			field        : 'noticeCode',
			title        : '公告编码',
			showOverflow : 'tooltip'
		},
		{
			field        : 'title',
			title        : '标题',
			showOverflow : 'tooltip'
		},
		{
			field        : 'isLongTime',
			title        : '是否长期',
			showOverflow : 'tooltip',
			cellRender   : {
				name   : 'n-switch',
				props  : {
					size           : 'large',
					checkedValue   : true,
					uncheckedValue : false,
					slots          : {
						checked   : '是',
						unchecked : '否'
					}
				},
				events : {
					toggleEvent : async (row: any) => toggleIsLongTime(row)
				}
			}
		},
		{
			field        : 'startTime',
			title        : '开始时间',
			showOverflow : 'tooltip'
		},
		{
			field        : 'endTime',
			title        : '结束时间',
			showOverflow : 'tooltip'
		},
		{
			field        : 'isHotspot',
			title        : '是否热点',
			showOverflow : 'tooltip',
			cellRender   : {
				name   : 'n-switch',
				props  : {
					size           : 'large',
					checkedValue   : true,
					uncheckedValue : false,
					slots          : {
						checked   : '是',
						unchecked : '否'
					}
				},
				events : {
					toggleEvent : async (row: any) => toggleHotSpot(row)
				}
			}
		},
		{
			field        : 'status',
			title        : '是否启用',
			showOverflow : 'tooltip',
			cellRender   : {
				name   : 'n-switch',
				props  : {
					size           : 'large',
					checkedValue   : true,
					uncheckedValue : false,
					slots          : {
						checked   : '启用',
						unchecked : '禁用'
					}
				},
				events : {
					toggleEvent : async (row: any) => toggleStatus(row)
				}
			}
		},
		{
			title        : '操作',
			showOverflow : 'tooltip',
			slots        : {
				default : 'operate'
			}
		}
	],
	data           : [],
	// @ts-ignore
	onPageChange : async (params: any) => changePage(params)
});
// -------------------------------------------------------------------------------------
const addModalConfig = reactive({
	reLoad : () => initGrid()
});
const editModalConfig = reactive({
	reLoad : () => initGrid()
});
const infoModalConfig = reactive({
	reLoad : async () => initGrid()
});
// -------------------------------------------------------------------------------------
const vxeGridRef = ref<VxeGridInstance>();
const addModalRef = ref<InstanceType<typeof AddModal>>();
const editModalRef = ref<InstanceType<typeof EditModal>>();
const infoModalRef = ref<InstanceType<typeof InfoModal>>();
// -------------------------------------------------------------------------------------
onBeforeMount(() => {
});
onMounted(() => {
	initGrid();
});
/**
 * 初始化表格
 */
const initGrid = async () => {
	gridConfig.loading = true;
	vxeGridRef.value?.clearCurrentRow();
	vxeGridRef.value?.clearCurrentColumn();
	axios<any, JsonResultProps<any>, any>({
		method : 'POST',
		url    : '/notice/pagingList',
		data   : {
			...gridConfig.formConfig?.data,
			tenantCode : sessionStorage.getItem('loginTenantCode'),
			pageNum    : gridConfig.pagerConfig!.currentPage,
			pageSize   : gridConfig.pagerConfig!.pageSize
		}
	}).then((jsonResult: JsonResultProps<any>) => {
		if (jsonResult['status']) {
			gridConfig.data = jsonResult.data.records;
			gridConfig.pagerConfig!.total = jsonResult.data.total;
		} else {
			VxeUI.modal.message({ content : jsonResult['msg'], status : 'warning', id : 'failedMessage' });
			gridConfig['loading'] = false;
		}
		gridConfig['loading'] = false;
	}).catch((error: unknown) => {
		console.error(error);
		VxeUI.modal.message({ content : '系统异常,请稍后再试', status : 'error', id : 'errorMessage' });
		gridConfig['loading'] = false;
	});
};
const changePage = async ({ currentPage, pageSize }: { currentPage: number, pageSize: number }) => {
	gridConfig['pagerConfig']!['currentPage'] = currentPage;
	gridConfig['pagerConfig']!['pageSize'] = pageSize;
	await initGrid();
};
const reset = () => {
	gridConfig.formConfig!.data = {
		id          : null,
		title       : null,
		releaseDate : null,
		isHotSpot   : null
	};
	initGrid();
};
const toggleIsLongTime = async (row: SystemNoticeInfoProps) => {
	axios<any, JsonResultProps<any>, any>({
		method : 'PATCH',
		url    : `/notice/isLongTime/${sessionStorage.getItem('loginTenantCode')}/${row.noticeCode}`
	}).then((jsonResult: any) => {
		if (jsonResult['status']) {
			VxeUI.modal.message({
				content : jsonResult['msg'],
				status  : 'success',
				id      : 'successMessage'
			});
		} else {
			VxeUI.modal.message({
				content : jsonResult['msg'],
				status  : 'warning',
				id      : 'failedMessage'
			});
		}
		initGrid();
	}).catch(errorObj => {
		console.error(errorObj);
		VxeUI.modal.message({
			content : '系统异常,请稍后再试',
			status  : 'error',
			id      : 'errorMessage'
		});
	});
};
const toggleHotSpot = async (row: any) => {
	axios<any, JsonResultProps<any>, any>({
		method : 'PATCH',
		url    : `/notice/hotspot/${sessionStorage.getItem('loginTenantCode')}/${row.noticeCode}`
	}).then((jsonResult: any) => {
		if (jsonResult['status']) {
			VxeUI.modal.message({
				content : jsonResult['msg'],
				status  : 'success',
				id      : 'successMessage'
			});
		} else {
			VxeUI.modal.message({
				content : jsonResult['msg'],
				status  : 'warning',
				id      : 'failedMessage'
			});
		}
		initGrid();
	}).catch(errorObj => {
		console.error(errorObj);
		VxeUI.modal.message({
			content : '系统异常,请稍后再试',
			status  : 'error',
			id      : 'errorMessage'
		});
	});
};
const toggleStatus = async (row: any) => {
	axios<any, JsonResultProps<any>, any>({
		method : 'PATCH',
		url    : `/notice/status/${sessionStorage.getItem('loginTenantCode')}/${row.noticeCode}`
	}).then((jsonResult: any) => {
		if (jsonResult['status']) {
			VxeUI.modal.message({
				content : jsonResult['msg'],
				status  : 'success',
				id      : 'successMessage'
			});
		} else {
			VxeUI.modal.message({
				content : jsonResult['msg'],
				status  : 'warning',
				id      : 'failedMessage'
			});
		}
		initGrid();
	}).catch(errorObj => {
		console.error(errorObj);
		VxeUI.modal.message({
			content : '系统异常,请稍后再试',
			status  : 'error',
			id      : 'errorMessage'
		});
	});
};
/*const detail = async (row: SystemNoticeProps) => {
 infoModalRef.value?.showModal(row);
 };*/
const add = async () => {
	addModalRef.value?.showModal();
};
const edit = async (row: SystemNoticeProps) => {
	editModalRef.value?.showModal(row);
};
const remove = async (row: any) => {
	VxeUI.modal.confirm({
		content : '您确定要删除该公告吗?',
		title   : '你确定吗?',
		id      : 'deleteModalUnique'
	}).then((type: any) => {
		if ('confirm' === type) {
			axios<any, JsonResultProps<any>, any>({
				method : 'DELETE',
				url    : `/notice/remove/${sessionStorage.getItem('loginTenantCode')}/${row.noticeCode}`
			}).then((jsonResult: any) => {
				if (jsonResult['status']) {
					VxeUI.modal.message({
						content : jsonResult['msg'],
						status  : 'success',
						id      : 'successMessage'
					});
				} else {
					VxeUI.modal.message({
						content : jsonResult['msg'],
						status  : 'warning',
						id      : 'failedMessage'
					});
				}
				initGrid();
			}).catch(errorObj => {
				console.error(errorObj);
				VxeUI.modal.message({
					content : '系统异常,请稍后再试',
					status  : 'error',
					id      : 'errorMessage'
				});
			});
		}
	});
};
// 导出方法
defineExpose({});
</script>
<style scoped lang='scss'>
.noticeMaintain-container{
	box-sizing :border-box;
	margin     :0;
	padding    :0;
	border     :0;
	width      :100%;
	height     :100%;
}
</style>